import { Editor, Element, Frame, useEditor } from '@craftjs/core';
import { Col, Row } from 'antd';
import * as BaseComponents from './BaseComponents';
import { Container } from './components/Container';
import { SettingPanel } from './settingPanel';
import { ToolBox } from './toolBox';
import { Tools } from './tools';

type StageProps = {
  initData?: string;
};

type TemplateProps = {
  initData?: string;
  preview?: boolean;
};

const Stage: React.FC<StageProps> = ({ initData }) => {
  const { preview } = useEditor((state) => ({
    preview: !state.options.enabled,
  }));

  return (
    <Row style={{ height: 'calc(100vh - 64px)', border: '1px solid #9d9d9d' }}>
      {!preview && (
        <Col flex={'200px'}>
          <ToolBox />
        </Col>
      )}
      <Col flex={'1'} style={{ overflowX: 'auto' }}>
        <Tools />
        <Frame data={initData}>
          {/* <Element canvas is={Container} /> */}
          <Element
            canvas
            is="div"
            style={{
              height: 'calc(100% - 52px)',
              padding: 20,
              boxSizing: 'border-box',
              overflow: 'auto',
            }}
          />
        </Frame>
      </Col>
      {!preview && (
        <Col flex={'350px'} style={{ height: '100%', overflow: 'auto' }}>
          <SettingPanel />
        </Col>
      )}
    </Row>
  );
};

const Template: React.FC<TemplateProps> = ({ initData, preview }) => {
  const enabled = preview === undefined ? false : Boolean(Number(preview));

  return (
    <Editor resolver={{ Container, ...BaseComponents }} enabled={enabled}>
      <Stage initData={initData} />
    </Editor>
  );
};

export default Template;
